package br.com.sovi.persistence;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.PrimaryKeyJoinColumn;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.openinsula.arena.hibernate.entity.BaseEntity;
import org.springframework.util.ObjectUtils;

@Entity
public class Dispositivo extends BaseEntity<Long> {
	private static final long serialVersionUID = 1L;

	@Column
	private String nome;

	@Column(unique = true, nullable = false)
	private String serial;

	@Column(length = 100)
	private String senha;

	@ManyToOne
	@JoinColumn(name = "usuario_fk")
	private Usuario usuario;
	
	@OneToMany(mappedBy = "dispositivo", cascade = CascadeType.ALL)
	@OrderBy("id desc")
	private List<Ponto> pontos = new ArrayList<Ponto>();

	@OneToOne
	@PrimaryKeyJoinColumn
	private Cerca cerca;

	public Dispositivo() {
	}

	@Override
	public String toString() {
		return String.format("[%s: id= %s], serial= %s", getClass().getName(), ObjectUtils.nullSafeToString(getId()),
				ObjectUtils.nullSafeToString(serial));
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}

		if (obj == null || !getClass().isAssignableFrom(obj.getClass())) {
			return false;
		}

		Dispositivo other = (Dispositivo) obj;

		return new EqualsBuilder().append(this.serial, other.serial).isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(serial).toHashCode();
	}

	public void addPonto(Ponto bean) {
		pontos.add(bean);
		bean.setDispositivo(this);
		
	}

	public String getSerial() {
		return serial;
	}

	public void setSerial(String serial) {
		this.serial = serial;
	}

	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}
	
	public String getNome() {
		return nome;
	}

	public void setNome(String nome) {
		this.nome = nome;
	}

	public List<Ponto> getPontos() {
		return pontos;
	}

	public void setPontos(List<Ponto> pontos) {
		this.pontos = pontos;
	}

	public void setCerca(Cerca cerca) {
		this.cerca = cerca;
	}

	public Cerca getCerca() {
		return cerca;
	}

}
